package liportest.testabstract;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@Order(value = Ordered.HIGHEST_PRECEDENCE + 1)
public class CarFactory implements CommandLineRunner {
    private static final ConcurrentHashMap<String, Car> COLLECT_STRATEGY = new ConcurrentHashMap<>();


    public static Car invoke(String protocol) {
        return COLLECT_STRATEGY.get(protocol);
    }

    @Override
    public void run(String... args) throws Exception {
        // spi load and registry protocol and collect instance
        ServiceLoader<Car> loader = ServiceLoader.load(Car.class, Car.class.getClassLoader());
        for (Car collect : loader) {
            COLLECT_STRATEGY.put(collect.supportProtocol(), collect);
        }
    }


}
